const fs = require('fs/promises');
const path = require('path');
const rimraf = require('rimraf');

const basePath = path.resolve(__dirname, '../dist');

// 可配置的包含插件名称数组（只保留这些插件）
const includePlugins = [
    'SUNO',      // 示例：只包含 SUNO 插件这里suno被改成了SUNO
    // 在这里添加更多你想要保留的插件名称
];

async function run() {
    console.log('生成json文件...');

    // 确保 dist 目录存在
    if (!await fs.stat(basePath).catch(() => false)) {
        await fs.mkdir(basePath, { recursive: true });
    }

    const pluginPath = path.resolve(basePath, '_plugins');
    await rimraf(pluginPath);
    await fs.mkdir(pluginPath, { recursive: true });

    const bundledPlugins = await fs.readdir(basePath);
    console.log('发现的插件文件夹:', bundledPlugins);

    const output = {
        desc: "此链接为 MusicAI 插件，插件开发及使用方式参考 网站正在搭建中...",
        plugins: []
    };

    await Promise.all(bundledPlugins.map(async (bundleFolder) => {
        if (!bundleFolder.startsWith('_')) {
            try {
                const targetPluginPath = path.resolve(basePath, bundleFolder, 'index.js');
                console.log(`处理插件: ${bundleFolder}, 路径: ${targetPluginPath}`);
                await fs.stat(targetPluginPath);
                const origin = await fs.readFile(targetPluginPath, 'utf-8');
                console.log(`插件 ${bundleFolder} 的 index.js 内容:`, origin);

                const mexports = origin.match(/module.exports\s*=\s*([\s\S]*)$/);
                if (!mexports) {
                    throw new Error('未找到 module.exports');
                }
                const platformMatch = mexports[1].match(/platform:\s*['"`](.*)['"`]/);
                if (!platformMatch) {
                    throw new Error('未找到 platform 字段');
                }
                const platform = platformMatch[1];
                const version = mexports[1].match(/version:\s*['"`](.*)['"`]/)?.[1];
                const srcUrl = mexports[1].match(/srcUrl:\s*['"`](.*)['"`]/)?.[1];
                const imageUrl = mexports[1].match(/imageUrl:\s*['"`](.*)['"`]/)?.[1];

                // 检查是否在包含列表中
                if (!includePlugins.includes(platform)) {
                    console.log(`跳过插件: ${platform} (不在包含列表中)`);
                    return;
                }

                // 创建插件对象
                const plugin = {
                    name: platform,
                    imageUrl: imageUrl || '', // 如果没有 imageUrl，设为空字符串
                    url: srcUrl,
                    version: version
                };

                output.plugins.push(plugin);
                console.log(`成功添加插件: ${platform}`);
            } catch (e) {
                console.warn(`[警告] 处理插件 ${bundleFolder} 失败:`, e.message);
            }
        }
    }));

    console.log('最终生成的 plugins 数组:', output.plugins);
    await fs.writeFile(path.resolve(pluginPath, 'plugins.json'), JSON.stringify(output, null, 2));
    await fs.copyFile(path.resolve(pluginPath, 'plugins.json'), path.resolve(__dirname, '../plugins.json'));
    console.log('done√');
}

run().catch(err => {
    console.error('构建失败:', err);
    process.exit(1);
});